package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        String s = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //isnotblank只有“abc”才过，空串“”，null，占位符等不过
        if (StrUtil.isNotBlank(s)){
            Shop bean = JSONUtil.toBean(s, Shop.class);
            return Result.ok(bean);
        }
        //空值不为null
        if (s != null){
            return Result.fail("店铺不存在");
        }


        //缓存未命中
        String key = "lock::shop" + id;
       Boolean istrylock =trylock(key);
        Shop byId = getById(id);
        //自定义锁，考虑缓存击穿问题
        try {
            if (!istrylock){
                Thread.sleep(50);
                return queryById(id);
            }
            // 查询数据库没值，往缓存存一个空值，防止缓存穿透,未命中
            if (byId == null){
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return Result.fail("店铺不存在,添加空集合，防止缓存击穿");
            }
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(byId),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(key);
        }
        return Result.ok(byId);
    }
    //sent设置的key值为唯一的
    public Boolean trylock(String key){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }
    public void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    public Result updateByredis(Shop shop) {
        if (shop.getId() == null){
            return Result.fail("店铺id为空");
        }
        updateById(shop);
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
}
